package com.menglei.dailytasks.m0716;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class SimpleContentProvider extends ContentProvider {
    private static final String TAG = "SimpleContentProvider:";
    private DBHelper dbHelper;
    private final String TABLE_NAME = "test_db";
    private SQLiteDatabase sqLiteDatabase;
    private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        MATCHER.addURI("com.example.demo0716.custom.SimpleContentProvider", "users", 1);
        MATCHER.addURI("com.example.demo0716.custom.SimpleContentProvider", "users/#", 2);
    }

    @Override
    public boolean onCreate() {
        dbHelper = new DBHelper(getContext(), TABLE_NAME, null, 1);
        sqLiteDatabase = dbHelper.getWritableDatabase();
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String orderBy) {
        switch (MATCHER.match(uri)) {
            case 1:
                return sqLiteDatabase.query("user", projection, selection, selectionArgs, null, null, orderBy);
            case 2:
                long id = ContentUris.parseId(uri);
                String select = "_id=" + id;
                if (selection != null && !selection.equals("")) {
                    select = select + "and" + selection;
                }
                return sqLiteDatabase.query("user", projection, select, selectionArgs, null, null, orderBy);
            default:
                throw new IllegalArgumentException("不明uri"+uri);
        }
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
        Log.d(TAG, "insert");
        switch (MATCHER.match(uri)) {
            case 1:
                long id = sqLiteDatabase.insert("user", null, contentValues);
                Uri insertUri = ContentUris.withAppendedId(uri, id);
                getContext().getContentResolver().notifyChange(insertUri, null);
                Log.d(TAG, "insert" + contentValues.get("name"));
                return insertUri;
            default:
                throw new IllegalArgumentException("This is unKnow uri:" + uri);

        }
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
        return 0;
    }


}
